package mju.cxf.controller.employee;

import mju.cxf.constant.JwtClaimsConstant;
import mju.cxf.constant.MessageConstant;
import mju.cxf.dto.AdminLoginDTO;
import mju.cxf.dto.EmployeeDTO;
import mju.cxf.dto.EmployeeLoginDTO;
import mju.cxf.dto.ResetPasswordDTO;
import mju.cxf.entity.Admin;
import mju.cxf.entity.Employee;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mju.cxf.properties.JwtProperties;
import mju.cxf.result.Result;
import mju.cxf.service.EmployeeService;
import mju.cxf.utils.JwtUtil;
import mju.cxf.vo.AdminLoginVO;
import mju.cxf.vo.EmployeeLoginVO;
import mju.cxf.vo.EmployeeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工对员工操作相关接口
 */
@RestController
@Api(tags = "员工对自己操作接口列表")
@RequestMapping("/employee/api/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService  employeeService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登陆接口
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登陆员工用户")
    @CrossOrigin
    public Result<EmployeeLoginVO> loginEmployee(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        Employee employee = employeeService.loginEmployee(employeeLoginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.JWT_ID, employee.getId());
        claims.put(JwtClaimsConstant.ROLE, "EMPLOYEE");

        // 生成令牌
        String token = JwtUtil.createJWT(jwtProperties.getJwtSecretKey(), jwtProperties.getJwtTtl(), claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .employee(employee)
                .token(token)
                .build();
        //密码设置为空返回
        employeeLoginVO.getEmployee().setPassword(null);
        return Result.success(employeeLoginVO);
    }

    /**
     * 修改员工密码
     *
     * @param resetPasswordDTO
     * @return
     */
    @PutMapping("/reset")
    @ApiOperation(value = "修改管理员密码")
    public Result<String> updateEmployeePassword(@RequestBody ResetPasswordDTO resetPasswordDTO) {
        System.out.println(resetPasswordDTO);
        return employeeService.updatePassword(resetPasswordDTO) ?
                Result.success(MessageConstant.SUCCESS_MESSAGE) :
                Result.error(MessageConstant.UPDATE_PASSWORD_ERROR);
    }

    /**
     * 更新员工信息
     * @return
     */
    @PutMapping
    @ApiOperation(value = "修改员工信息")
    public Result<String> updateEmployee(@RequestBody EmployeeDTO employeeDTO) {
        Employee employee =new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employeeService.updateById(employee);
        return Result.success();
    }
}
